package cn.com.api.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.api.entity.ApiD_invite_record;
import cn.com.api.entity.ApiD_proxy;
import cn.com.api.entity.ApiDingDan;
import cn.com.api.entity.ApiShop;
import cn.com.api.entity.ApiSmslog;
import cn.com.api.entity.ApiT_member_entrepreneur;
import cn.com.api.entity.ApiT_member_idcard;
import cn.com.api.entity.ApiT_member_partner;
import cn.com.api.entity.ApiT_member_partner_task;
import cn.com.api.entity.ApiT_member_task_process;
import cn.com.api.entity.ApiT_member_wemedia;
import cn.com.api.entity.ApiT_order;
import cn.com.api.entity.ApiT_user_cash_records;
import cn.com.api.entity.ApiTmember;
import cn.com.api.entity.ApiU_bonus_detail;
import cn.com.api.entity.ApiU_circle;
import cn.com.api.entity.ApiU_dynamic;
import cn.com.api.entity.ApiU_dynamic_source;
import cn.com.api.entity.ApiU_message;
import cn.com.api.entity.ApiU_see_his;
import cn.com.api.entity.ApiU_share_bonus;
import cn.com.api.entity.ApiU_user_experence;
import cn.com.api.entity.ApiU_user_friend;
import cn.com.api.entity.ApiU_user_friend_group;
import cn.com.api.entity.ApiU_user_friend_setting;
import cn.com.api.entity.MemberObject;
import cn.com.api.entity.U_label;
import cn.com.api.entity.memberHomePage;
import cn.com.api.mapper.ApiD_invite_recordMapper;
import cn.com.api.mapper.ApiD_proxyMapper;
import cn.com.api.mapper.ApiDingDanMapper;
import cn.com.api.mapper.ApiShopsMapper;
import cn.com.api.mapper.ApiSmslogMapper;
import cn.com.api.mapper.ApiT_member_entrepreneurMapper;
import cn.com.api.mapper.ApiT_member_idcardMapper;
import cn.com.api.mapper.ApiT_member_partnerMapper;
import cn.com.api.mapper.ApiT_member_partner_taskMapper;
import cn.com.api.mapper.ApiT_member_task_processMapper;
import cn.com.api.mapper.ApiT_member_wemediaMapper;
import cn.com.api.mapper.ApiT_orderMapper;
import cn.com.api.mapper.ApiT_user_cash_recordsMapper;
import cn.com.api.mapper.ApiTmemberMapper;
import cn.com.api.mapper.ApiU_bonus_detailMapper;
import cn.com.api.mapper.ApiU_circleMapper;
import cn.com.api.mapper.ApiU_circle_memberMapper;
import cn.com.api.mapper.ApiU_dynamicMapper;
import cn.com.api.mapper.ApiU_dynamic_sourceMapper;
import cn.com.api.mapper.ApiU_messageMapper;
import cn.com.api.mapper.ApiU_see_hisMapper;
import cn.com.api.mapper.ApiU_user_experenceMapper;
import cn.com.api.mapper.ApiU_user_friendMapper;
import cn.com.api.mapper.ApiU_user_friend_settingMapper;
import cn.com.api.mapper.ApiU_user_labelMapper;
import cn.com.api.mapper.U_labelMapper;
import cn.com.api.service.ApiCommonService;
import cn.com.api.service.ApiMemberService;
import cn.com.api.service.ApiSmslogService;
import cn.com.api.service.ApiU_share_bonusService;
import cn.com.api.service.ApiU_user_friend_groupService;
import cn.com.api.service.CheckService;
import cn.com.util.CipherUtil;
import cn.com.util.DateUtil;
import cn.com.util.PageInfo;
import cn.com.util.QRCodeUtils;
import cn.com.util.SendMsgUtil;
import cn.com.util.UUIDUtil;
import cn.com.util.Util;
import cn.com.util.Utils;

import com.ibm.icu.text.DecimalFormat;

@Service
public class ApiMemberServiceImpl implements ApiMemberService {
	@Autowired
	private ApiU_bonus_detailMapper apiU_bonus_detailMapper;
	@Autowired
	private ApiTmemberMapper apiTmemberMapper;
	@Autowired
	private ApiT_member_idcardMapper apiT_member_idcardMapper;
	@Autowired
	private ApiCommonService apiCommonService;
	@Autowired
	private ApiSmslogMapper apiSmslogMapper;
	@Autowired
	private ApiSmslogService apiSmslogService;
	@Autowired
	private ApiShopsMapper apiShopsMapper;
	@Autowired
	private ApiU_share_bonusService apiU_share_bonusService;
	@Autowired
	private ApiU_user_friendMapper apiU_user_friendMapper;
	@Autowired
	private ApiU_user_experenceMapper apiU_user_experenceMapper;
	@Autowired
	private ApiT_member_entrepreneurMapper apiT_member_entrepreneurMapper;
	@Autowired
	private ApiT_member_partnerMapper apiT_member_partnerMapper;
	@Autowired
	private ApiT_member_wemediaMapper apiT_member_wemediaMapper;
	@Autowired
	private ApiT_user_cash_recordsMapper apiT_user_cash_recordsMapper;
	@Autowired
	private CheckService checkService;
	@Autowired
	private U_labelMapper UlabelMapper;
	@Autowired
	private ApiU_circleMapper apiU_circleMapper;
	@Autowired
	private ApiU_circle_memberMapper apiU_circle_memberMapper;
	@Autowired
	private ApiU_dynamicMapper apiU_dynamicMapper;
	@Autowired
	private ApiU_dynamic_sourceMapper apiU_dynamic_sourceMapper;
	@Autowired
	private ApiU_see_hisMapper apiU_see_hisMapper;
	@Autowired
	private ApiT_member_task_processMapper apiT_member_task_processMapper;
	@Autowired
	private ApiT_member_partner_taskMapper apiT_member_partner_taskMapper;
	@Autowired
	private ApiU_user_labelMapper apiU_user_labelMapper;
	@Autowired
	private ApiU_user_friend_groupService apiU_user_friend_groupService;
	@Autowired
	private ApiU_messageMapper apiU_messageMapper;
	@Autowired
	private ApiU_user_friend_settingMapper apiU_user_friend_settingMapper;
	@Autowired
	private ApiD_proxyMapper apiD_proxyMapper;
	@Autowired
	private ApiDingDanMapper apiDingDanMapper;
	@Autowired
	private ApiT_orderMapper apiT_orderMapper;
	@Autowired
	private ApiD_invite_recordMapper invite_recordMapper;
	private static Logger logger = Logger.getLogger(ApiMemberServiceImpl.class);

	/**
	 * 登录成功后返回一个新的token
	 */
	@Transactional
	@Override
	public ApiTmember login(ApiTmember member) {
		ApiTmember apiMember = apiTmemberMapper.login(member.getCuserid(),
				member.getCpass());
		if (apiMember != null) {
			apiMember.setIs_login(1);
			apiMember.setDeviceid(member.getDeviceid());
			apiMember.setDevicetype(member.getDevicetype());
			apiMember.setLongitude(member.getLongitude());
			apiMember.setLatitude(member.getLatitude());
			// token
			apiCommonService.updateApiTmember(apiMember);

		}
		return apiMember;
	}

	/**
	 * 网站前端登陆
	 */
	@Transactional
	@Override
	public ApiTmember weblogin(ApiTmember member) {
		ApiTmember apiMember = apiTmemberMapper.login(member.getCuserid(),
				member.getCpass());
		return apiMember;
	}

	/**
	 * 发送验证码
	 */
	@Transactional
	@Override
	public String sendIdentifyCode(String cTel, int type) throws Exception {
		// 发验证码，并保存
		// 产生验证码---
		String ran = Utils.customNum(10000); // 随机码
		// String msg = Utils.getMessage(null, "API_MSGCONTENT_REGIST", new
		// String[] { ran }); // 发送出去的信息内容
		String msg = "您好，您的验证码是" + ran;
		// System.out.println("验证码：" + msg);
		// sendMessage.batchSend(cTel, msg);
		String ret_status = SendMsgUtil.sendSMS(msg, cTel,
				SendMsgUtil.sprdid_notice);
		if (ret_status.length() > 0) { // 发送成功
			ApiSmslog apiSmslog = new ApiSmslog();
			apiSmslog.setcTel(cTel);
			apiSmslog.setcText(msg); // 短消息内容
			apiSmslog.setCode(ran);
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			apiSmslog.setcAppDate(dateFormat.format(now));
			apiSmslog.setcJid("0");
			apiSmslog.setcSid("0");
			apiSmslog.setType(type);// 0用户注册
			apiSmslog.setStatus(0);// 0未验证
			apiSmslogService.saveSmslog(apiSmslog);
		} else {
			return "";
		}

		return ran;
	}

	@Transactional
	@Override
	public ApiTmember regist(String path, ApiTmember member, ApiSmslog apiSmslog) {
		// 更新验证码状态
		apiSmslogService.updateSmslog(apiSmslog);
		// 保存注册用户信息
		apiTmemberMapper.saveApiTmember(member);
		ApiTmember apiTmember = apiTmemberMapper.findMemberByCuserid(member
				.getCuserid());
		// 加入用户二维码
		String userCode = setUserQRcode(path, apiTmember.getCid().toString());
		apiTmember.setInvite_code(userCode);

		// 用户的收款二维码
		String receiveqrcode = setReceiveQRcode(apiTmember.getCid().toString());
		apiTmember.setReceive_qrcode(receiveqrcode);

		// 更新注册用户信息
		apiCommonService.updateApiTmember(apiTmember);
		// 推荐用户奖励优惠券
		// apiT_recommend_couponService.newLoginToTakeCoupons(member.getCuserid());

		// 设置默认的文章关注频道
		this.checkService
				.setHeadLineDefaultCate(apiTmember.getCid().toString());

		// 创建好友消息分组(我的消息)
		ApiU_user_friend_group f_group = new ApiU_user_friend_group();
		f_group.setAdd_time(Util.CurrentTime());
		f_group.setCreate_id(apiTmember.getCid().toString());
		f_group.setGroup_name("我的消息");
		f_group.setSort(0);
		this.apiU_user_friend_groupService
				.U_user_friend_groupInsertion(f_group);

		return apiTmember;
	}

	private String setUserQRcode(String path, String code) {
		String retCode = "";
		try {
			String qrCodeInfo = QRCodeUtils.baseUrl
					+ "/partner/sq-ziliao.html?code=" + "0:" + code;
			retCode = QRCodeUtils.createQrCode(qrCodeInfo, 300);
			return retCode;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			return retCode;
		}
	}

	private String setReceiveQRcode(String code) {
		String retCode = "";
		try {
			String qrCodeInfo = QRCodeUtils.baseUrl
					+ "/partner/sq-ziliao.html?code=" + "3:" + code;
			retCode = QRCodeUtils.createQrCode(qrCodeInfo, 300);
			return retCode;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			return retCode;
		}
	}

	@Override
	public ApiTmember loginByCode(String path, ApiTmember member,
			ApiSmslog apiSmslog) {
		// 更新验证码状态
		apiSmslogService.updateSmslog(apiSmslog);
		ApiTmember apiTmember = apiTmemberMapper.findMemberByCuserid(member
				.getCuserid());
		if (Util.isNull(apiTmember)) {
			// 保存注册用户信息
			String smcode = "SM" + System.currentTimeMillis();
			member.setSmcode(smcode);
			apiTmemberMapper.saveApiTmember(member);
			apiTmember = apiTmemberMapper.findMemberByCuserid(member
					.getCuserid());
			// 加入用户二维码
			String userCode = setUserQRcode(path, apiTmember.getCid()
					.toString());
			apiTmember.setInvite_code(userCode);
		}

		// 更新注册用户信息
		apiCommonService.updateApiTmember(apiTmember);

		// 设置默认的文章关注频道
		this.checkService
				.setHeadLineDefaultCate(apiTmember.getCid().toString());
		// ApiTmember apiTmember =
		// apiTmemberMapper.findMemberByCuserid(member.getCuserid());
		return apiTmember;
	}

	@Override
	public ApiTmember findMemberByCuserid(String cUserId) {
		ApiTmember member = apiTmemberMapper.findMemberByCuserid(cUserId);
		return member;
	}

	@Override
	public ApiTmember findMemberByCid(Integer cid) {
		ApiTmember member = apiTmemberMapper.findMemberByCid(cid);
		if (!Util.isNull(member)) {
			// 兴趣爱好是否设置
			Integer intCount = this.apiU_user_labelMapper.checkUserLabel(
					cid.toString(), 1);
			member.setIs_Interest(intCount);
			// 专业领域是否设置
			Integer intArea = this.apiU_user_labelMapper.checkUserLabel(
					cid.toString(), 3);
			member.setIs_Area(intArea);

			// 核伙人等级
			List<ApiT_member_partner_task> task_list = this.apiT_member_partner_taskMapper
					.getMemberTaskLevel(cid.toString());
			if (task_list.size() > 0) {
				member.setMember_level(task_list.get(0).getMember_level());
			}
			// else {
			// member.setMember_level(4);
			// }
		}
		return member;
	}

	@Override
	@Transactional
	public ApiTmember forgetCPass(ApiTmember member, ApiSmslog apiSmslog)
			throws Exception {
		// 更新用户信息-密码
		apiCommonService.updateApiTmemberPass(member);
		// 更新验证码状态-已验证
		apiSmslogService.updateSmslog(apiSmslog);
		// 更新用户token
		apiCommonService.updateApiTmember(member);
		return null;
	}

	@Override
	public void modifyApiTmemberByCuserid(Map map) {
		apiTmemberMapper.modifyApiTmemberByCuserid(map);
	}

	// 第三方登陆新加↓↓↓↓
	@Override
	public ApiTmember thirdLogin(ApiTmember apiTmember) {
		apiTmemberMapper.saveThirdTmember(apiTmember);
		return apiTmember;
	}

	// 第三方登陆新加↑↑↑↑

	@Override
	public ApiTmember updateThirdMember(ApiTmember member) {
		apiTmemberMapper.updateThirdMember(member);
		ApiTmember tmember = apiTmemberMapper.findMemberByCuserid(member
				.getCuserid());
		// 更新用户token
		apiCommonService.updateApiTmember(tmember);
		return tmember;
	}

	@Override
	public List<ApiTmember> findT_membersByRole(Integer c_mtype) {
		List<ApiTmember> types = apiTmemberMapper.findT_membersByRole(c_mtype);
		return types;
	}

	/**
	 * 校验手机号是否已注册
	 */
	@Override
	public ApiTmember checkMemberExist(String cUserId) {
		ApiTmember tmember = apiTmemberMapper.findMemberByCuserid(cUserId);
		return tmember;
	}

	/**
	 * 校验商铺手机号是否已注册
	 */
	@Override
	public boolean checkShopsExist(String cmobi) {
		List<ApiShop> list = new ArrayList<ApiShop>();
		list = apiShopsMapper.searchShopsByCmobi(cmobi);
		if (list.size() > 0) {
			return true;// 已存在
		}
		return false;// 不存在
	}

	@Override
	public ApiTmember isExistThirdLogin(Map<String, String> params) {
		String type = params.get("type");
		String openid = params.get("openId");
		System.out.println("type:" + type + "----openid:" + openid);
		ApiTmember tmember = apiTmemberMapper.isExistThirdLogin(type, openid);
		System.out.println("是否存在第三方的用户：" + tmember);
		// 更新用户token
		if (tmember != null) {// 存在 返回
			String deviceId = params.get("deviceId");
			String deviceType = params.get("deviceType");
			String thirdName = params.get("thirdName");
			if (!Util.isNull(deviceType)) {
				tmember.setDeviceid(deviceId);
				tmember.setDevicetype(Integer.parseInt(deviceType));
				// // 1-QQ 2-微信 3-新浪
				if (type.equals("1")) {
					tmember.setQq_name(thirdName);
				}
				if (type.equals("2")) {
					tmember.setWx_name(thirdName);
				}
				if (type.equals("3")) {
					tmember.setWb_name(thirdName);
				}

			}
			apiCommonService.updateApiTmember(tmember);
		}
		return tmember;
	}

	@Override
	public void thirdFirstLogin(String path, Map<String, String> params,
			Map<String, Object> map) {
		// String is_register = params.get("is_register");
		String type = params.get("type");
		String openId = params.get("openId");
		String deviceId = params.get("deviceId");
		String cPass = params.get("cPass");
		String thirdName = params.get("thirdName");
		String deviceType = params.get("deviceType");
		String cMob = params.get("cMob");
		String code = params.get("code");
		String Longitude = Util.isNull(params.get("Longitude")) == true ? ""
				: params.get("Longitude");
		String Latitude = Util.isNull(params.get("Latitude")) == true ? ""
				: params.get("Latitude");

		// String invite_code = params.get("invite_code");

		ApiTmember apiMember = checkMemberExist(cMob);
		if (Util.isNull(apiMember)) {// 未注册过---也未绑定过---新增一条到数据库里
			ApiSmslog apiSmslog = new ApiSmslog();
			apiSmslog.setcTel(cMob);
			apiSmslog.setCode(code);
			// 校验验证码是否正确
			if (apiSmslogService.checkCode(apiSmslog)) {
				apiMember = new ApiTmember();
				apiMember.setCmob(cMob);
				apiMember.setCuserid(cMob);
				apiMember.setCpass(CipherUtil.generatePassword(cPass));
				// apiMember.setCtname(thirdName);
				apiMember.setCnick(thirdName);
				apiMember.setLongitude(Longitude);
				apiMember.setLatitude(Latitude);
				String smcode = "SM" + System.currentTimeMillis();
				apiMember.setSmcode(smcode);

				// apiMember.setInvite_code(invite_code);//
				// 手机号存在的话，此次邀请码不起作用--邀请码可为空
				if (!Util.isNull(deviceType)) {
					apiMember.setDeviceid(deviceId);
					apiMember.setDevicetype(Integer.parseInt(deviceType));
				}
				apiMember.setThirdType(Integer.valueOf(type));
				// 1-QQ 2-微信 3-新浪
				if ("1".equals(type)) {
					apiMember.setQq_openid(openId);
					apiMember.setQq_name(thirdName);
				}
				if ("2".equals(type)) {
					apiMember.setOpenid(openId);
					apiMember.setWx_name(thirdName);
				}
				if ("3".equals(type)) {
					apiMember.setSina_openid(openId);
					apiMember.setWb_name(thirdName);
				}
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"yyyy/MM/dd HH:mm:ss");
				apiMember.setCregdate(dateFormat.format(new Date()));
				apiMember.setCmtype(0);// 0-用户
				// apiMember.setClogdate(dateFormat.format(new Date()));

				apiTmemberMapper.saveApiTmember(apiMember);

				ApiTmember apiTmember = this.apiTmemberMapper
						.findMemberByCuserid(cMob);
				// 加入用户二维码
				String userCode = setUserQRcode(path, apiTmember.getCid()
						.toString());

				apiTmember.setInvite_code(userCode);

				// 兴趣爱好是否设置
				Integer intCount = this.apiU_user_labelMapper.checkUserLabel(
						apiTmember.getCid().toString(), 1);
				apiMember.setIs_Interest(intCount);
				// 专业领域是否设置
				Integer intArea = this.apiU_user_labelMapper.checkUserLabel(
						apiTmember.getCid().toString(), 3);
				apiMember.setIs_Area(intArea);
				// 核伙人等级
				List<ApiT_member_partner_task> task_list = this.apiT_member_partner_taskMapper
						.getMemberTaskLevel(apiTmember.getCid().toString());
				if (task_list.size() > 0) {
					apiMember.setMember_level(task_list.get(0)
							.getMember_level());
				}
				// else {
				// apiMember.setMember_level(4);
				// }

				apiCommonService.updateApiTmember(apiTmember);

				// 设置默认的文章关注频道
				this.checkService.setHeadLineDefaultCate(apiTmember.getCid()
						.toString());

				// 创建好友消息分组(我的消息)
				ApiU_user_friend_group f_group = new ApiU_user_friend_group();
				f_group.setAdd_time(Util.CurrentTime());
				f_group.setCreate_id(apiTmember.getCid().toString());
				f_group.setGroup_name("我的消息");
				f_group.setSort(0);
				this.apiU_user_friend_groupService
						.U_user_friend_groupInsertion(f_group);

				// 推荐用户奖励优惠券
				// apiT_recommend_couponService.newLoginToTakeCoupons(apiMember.getCuserid());

				// 缩略图 头像60*60
				String header = apiTmember.getCavatar()
						+ "?imageView2/1/w/60/h/60";
				apiTmember.setCavatar(header);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "绑定手机成功！");
				map.put("datas", apiTmember);
			} else {
				map.put(Utils.RESULT, "0002");
				map.put(Utils.MESSAGE, "验证码不匹配，请重新填写！");
			}
		} else {// 数据库有这个手机号的用户 //1-QQ 2-微信 3-新浪----------------手机号已存在
			ApiSmslog apiSmslog = new ApiSmslog();
			apiSmslog.setcTel(cMob);
			apiSmslog.setCode(code);
			// 校验验证码是否正确
			if (apiSmslogService.checkCode(apiSmslog)) {
				// 验证密码
				if (checkService.checkLogin(params, map)) {
					apiMember.setLongitude(Longitude);
					apiMember.setLatitude(Latitude);

					boolean flag = false;
					if ("1".equals(type)) {// 更新
						// && apiMember.getQq_openid().equals("")
						flag = true;
						apiMember.setQq_openid(openId);
						apiMember.setQq_name(thirdName);
					}
					if ("2".equals(type)) {// 更新
						// && apiMember.getOpenid().equals("")
						flag = true;
						apiMember.setOpenid(openId);
						apiMember.setWx_name(thirdName);
					}
					if ("3".equals(type)) {// 更新
						// && apiMember.getSina_openid().equals("")
						flag = true;
						apiMember.setSina_openid(openId);
						apiMember.setWb_name(thirdName);
					}
					if (flag) {// 更新--不要重新登录
						if (!Util.isNull(deviceType)) {
							apiMember.setDeviceid(deviceId);
							apiMember.setDevicetype(Integer
									.parseInt(deviceType));
						}
						apiCommonService.updateApiTmember(apiMember);
						// // 设置默认的文章关注频道
						// this.checkService.setHeadLineDefaultCate(apiMember.getCid().toString());
						// 核伙人等级
						List<ApiT_member_partner_task> task_list = this.apiT_member_partner_taskMapper
								.getMemberTaskLevel(apiMember.getCid()
										.toString());
						if (task_list.size() > 0) {
							apiMember.setMember_level(task_list.get(0)
									.getMember_level());
						}
						// 缩略图 头像60*60
						String header = apiMember.getCavatar()
								+ "?imageView2/1/w/60/h/60";
						apiMember.setCavatar(header);
						map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
						map.put(Utils.MESSAGE, "绑定成功！");
						map.put("datas", apiMember);
					} else {
						map.put(Utils.RESULT, "0002");
						map.put(Utils.MESSAGE, "绑定手机失败！");
					}
				} else {
					map.put(Utils.RESULT, "0005");
					map.put(Utils.MESSAGE, "密码输入错误！");
				}

			} else {
				map.put(Utils.RESULT, "0004");
				map.put(Utils.MESSAGE, "验证码输入错误");
			}

		}
	}

	@Override
	public List<Map<String, Object>> searMemberByType(String type) {
		return apiTmemberMapper.searMemberByType(type);
	}

	@Override
	public ApiTmember CheckUser(Integer u_id, String pwd) {
		return apiTmemberMapper.CheckUser(u_id, pwd);
	}

	@Override
	// type:分类0文章分类， 1兴趣分类，2订阅分类， 3行业职位
	public List<U_label> searchUserInfoExtend(Integer user_id, Integer type) {
		List<U_label> labList = new ArrayList<U_label>();
		try {
			List<U_label> parentList = this.UlabelMapper.findParentByType(type);
			for (U_label lab : parentList) {
				List<U_label> childList = this.UlabelMapper.findItemByParentID(
						lab.getId(), user_id);
				lab.setChildLabel(childList);
				labList.add(lab);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.info("searchMyInterest: " + e.getStackTrace());
		}
		return labList;
	}

	// 根据认证编号获取人员信息
	@Override
	public ApiTmember findMemberByPartnerCode(String partner_code) {
		return apiTmemberMapper.findMemberByPartnerCode(partner_code);
	}

	// 更新用户首媒号
	public ApiTmember updateSmcodeByUid(Integer u_id, String sm_code) {
		apiTmemberMapper.updateSmcodeByUid(u_id, sm_code);
		return apiTmemberMapper.findMemberByCid(u_id);
	}

	// 主页获取企业主列表
	public List<MemberObject> getEntrepreneursList(String referee_id,
			PageInfo page) {
		Map<String, String> params = new HashMap<String, String>();
		// 推荐的企业主
		params.clear();
		params.put("referee_id", referee_id);
		params.put("status", "1");
		List<ApiT_member_entrepreneur> entre_member_list = this.apiT_member_entrepreneurMapper
				.findT_member_entrepreneursByMapListPage(params, page);

		List<MemberObject> entreMember_list = new ArrayList<MemberObject>();

		for (ApiT_member_entrepreneur tmember : entre_member_list) {
			MemberObject em = new MemberObject();
			em.setMember_id(tmember.getId());// 企业申请表ID
			em.setHead_img(tmember.getLogo_img());
			em.setMember_name(tmember.getCorp_sname());
			entreMember_list.add(em);
		}

		return entreMember_list;
	}

	// 主页获取核伙人列表
	public List<MemberObject> getPartnerList(String referee_id,
			PageInfo pageInfo) {
		// 邀请的核伙人
		List<ApiTmember> partner_list = this.apiTmemberMapper
				.findpartnerMemberByRefereeIDListPage(referee_id, pageInfo);
		List<MemberObject> partnerMember_list = new ArrayList<MemberObject>();

		for (ApiTmember tmember : partner_list) {
			MemberObject em = new MemberObject();
			em.setMember_id(tmember.getCid()); // 用户ID
			em.setHead_img(tmember.getCavatar());
			em.setMember_name(tmember.getCnick());
			partnerMember_list.add(em);
		}
		return partnerMember_list;
	}

	// 主页获取圈子列表
	public List<MemberObject> getCircleList(String user_id, PageInfo page) {
		Map<String, String> params = new HashMap<String, String>();
		params.clear();
		params.put("user_id", user_id);
		params.put("is_delete", "0");
		List<ApiU_circle> circle_list = this.apiU_circleMapper
				.findU_circlesByMapListPage(params, page);

		List<MemberObject> user_circle_list = new ArrayList<MemberObject>();

		for (ApiU_circle circle : circle_list) {
			MemberObject em = new MemberObject();
			em.setMember_id(circle.getId());// 圈子ID
			em.setHead_img(circle.getCircle_img());// 圈子头像
			em.setMember_name(circle.getCircle_name());// 圈子名
			em.setDesc(circle.getCircle_desc());// 圈子介绍
			user_circle_list.add(em);
		}
		return user_circle_list;
	}

	// 主页获取动态列表
	public List<MemberObject> getDynamicList(String user_id, PageInfo page) {
		Map<String, String> params = new HashMap<String, String>();
		// 动态
		params.clear();
		params.put("user_id", user_id);
		params.put("type", "0");
		List<ApiU_dynamic> dynamic_list = this.apiU_dynamicMapper
				.findU_dynamicsByMapListPage(params, page);
		List<MemberObject> user_dynamic_list = new ArrayList<MemberObject>();
		for (ApiU_dynamic dynamic : dynamic_list) {
			MemberObject em = new MemberObject();
			em.setMember_name(dynamic.getContext());// 动态文字
			em.setMember_id(dynamic.getId());// 动态ID
			em.setDesc(dynamic.getAdd_time());// 动态发布时间
			params.clear();
			params.put("dynamic_id", dynamic.getId().toString());
			// 动态中第一条图
			String img = "";
			List<ApiU_dynamic_source> dynamic_sources = this.apiU_dynamic_sourceMapper
					.findU_dynamic_sourcesByMap(params);
			if (dynamic_sources.size() == 0) {
				img = "";// 放入默认图片
			} else {
				img = dynamic_sources.get(0).getSource();
			}
			em.setHead_img(img);// 动态中第一张图片或视频
			user_dynamic_list.add(em);
		}
		return user_dynamic_list;
	}

	// 主页企业者列表查看企业信息
	public ApiT_member_entrepreneur getEntreInfo(String ent_id) {
		return this.apiT_member_entrepreneurMapper
				.findT_member_entrepreneurById(Integer.valueOf(ent_id));
	}

	// 获取用户主页信息 type 0:企业主 1：核伙人 2：自媒体 3：自己的主页面 4：别人的主页
	public memberHomePage getUserHomePageInfo(String user_id, Integer type,
			String my_id) {
		memberHomePage homePage = new memberHomePage();
		ApiTmember member = this.apiTmemberMapper.findMemberByCid(Integer
				.valueOf(user_id));

		homePage.setBackground(member.getBack_ground());

		Map<String, String> params = new HashMap<String, String>();
		PageInfo page = new PageInfo();
		page.setCurrentPage(1);
		page.setShowCount(5);

		if (type == 3 || type == 4) {
			// 个人地址
			String address = member.getCprovince() + member.getCcity()
					+ member.getCarea() + member.getCaddress();
			homePage.setAddress(address);
		}

		// 好友数
		Integer friend_count = this.apiU_user_friendMapper
				.getUserFriendCount(user_id);
		homePage.setFriend_count(friend_count);
		// 基本信息
		homePage.setUser_id(member.getCid());
		homePage.setBirthday(member.getCbirthday());
		homePage.setSex(member.getCsex());
		homePage.setIs_Entre(member.getVerify_entrepreneur());
		homePage.setIs_partner(member.getVerify_partner());
		homePage.setIs_wemedia(member.getVerify_media());

		List<ApiT_member_entrepreneur> entrepreneurs = new ArrayList<ApiT_member_entrepreneur>();
		if (type != 2) {
			params.clear();
			params.put("user_id", user_id);
			params.put("status", "1");
			entrepreneurs = this.apiT_member_entrepreneurMapper
					.findT_member_entrepreneursByMapListPage(params, page);
		}

		if (type == 0) {
			// 企业Logo
			if (entrepreneurs.size() > 0) {
				// 基本信息
				homePage.setHead_img(entrepreneurs.get(0).getLogo_img());
				homePage.setNick_name(entrepreneurs.get(0).getCorp_sname());

				// 企业信息
				homePage.setEntre_fname(entrepreneurs.get(0).getCorp_fname());
				homePage.setEntre_logo(entrepreneurs.get(0).getLogo_img());
				homePage.setEntre_brief(entrepreneurs.get(0).getCorp_brief());
				homePage.setEntre_url(entrepreneurs.get(0).getCorp_web());
				homePage.setServiceNo("10010");

				String address = entrepreneurs.get(0).getAddress();
				address = address.replaceAll("%", "");
				address = address.replaceAll(":", "");
				homePage.setAddress(address);

			}

			// 我的推荐人ID
			if (member.getReferee_uid().equals("")
					|| Util.isNull(member.getReferee_uid())) {
			} else {
				ApiTmember referee_member = this.apiTmemberMapper
						.findMemberByPartnerCode(member.getReferee_uid());
				homePage.setEntre_invite_id(referee_member.getCid());
				homePage.setEntre_invite_header(referee_member.getCavatar());
				homePage.setEntre_partner_code(referee_member.getPartner_code());
			}

		} else if (type == 1 || type == 3 || type == 4) {
			// 核伙人或自己
			// 基本信息
			homePage.setHead_img(member.getCavatar());
			homePage.setNick_name(member.getCnick());

			// 核伙人等级
			List<ApiT_member_partner_task> task_list = this.apiT_member_partner_taskMapper
					.getMemberTaskLevel(member.getCid().toString());
			if (task_list.size() > 0) {
				homePage.setPartner_level(task_list.get(0).getMember_level());
			}
			// else {
			// homePage.setPartner_level(4);
			// }

			homePage.setPartner_code(member.getPartner_code());
			// 职业经历
			List<ApiU_user_experence> experences = this.apiU_user_experenceMapper
					.getExperenceByUserID(user_id);
			homePage.setUser_experences(experences);
			homePage.setExperences_count(experences.size());

		} else if (type == 2) {
			// 自媒体
			// params.clear();
			// params.put("user_id", user_id);
			// params.put("status", "1");
			Map<String, Object> parms2 = new HashMap<String, Object>();
			parms2.put("user_id", Integer.valueOf(user_id));
			parms2.put("status", 1);
			List<ApiT_member_wemedia> wemedias = this.apiT_member_wemediaMapper
					.findT_member_wemediasByMap(parms2);
			if (wemedias.size() > 0) {
				// 基本信息
				homePage.setHead_img(wemedias.get(0).getMedia_header());
				homePage.setNick_name(wemedias.get(0).getMedia_title());
			}
		}

		if (type == 1 || type == 3) {
			// 推荐的企业主
			if (!Util.isNull(member.getPartner_code())) {
				params.clear();
				params.put("referee_id", member.getPartner_code());
				params.put("status", "1");
				List<ApiT_member_entrepreneur> entre_member_list = this.apiT_member_entrepreneurMapper
						.findT_member_entrepreneursByMapListPage(params, page);

				List<MemberObject> entreMember_list = new ArrayList<MemberObject>();

				for (ApiT_member_entrepreneur tmember : entre_member_list) {
					MemberObject em = new MemberObject();
					em.setMember_id(tmember.getId());
					em.setHead_img(tmember.getLogo_img());
					em.setMember_name(tmember.getCorp_sname());
					entreMember_list.add(em);
				}
				// 推荐企业主列表
				homePage.setEntre_list(entreMember_list);
				// 推荐企业主人数
				homePage.setEntre_count(entre_member_list.size());

				// 邀请的核伙人
				List<ApiTmember> partner_list = this.apiTmemberMapper
						.findpartnerMemberByRefereeID(member.getPartner_code());
				List<MemberObject> partnerMember_list = new ArrayList<MemberObject>();

				for (ApiTmember tmember : partner_list) {
					MemberObject em = new MemberObject();
					em.setMember_id(tmember.getCid());
					em.setHead_img(tmember.getCavatar());
					em.setMember_name(tmember.getCnick());
					partnerMember_list.add(em);
				}
				homePage.setPartner_list(partnerMember_list);
				homePage.setPartner_count(partner_list.size());

				params.clear();
				params.put("user_id", member.getCid().toString());
				params.put("status", "1");
				List<ApiT_member_partner> partner_members = this.apiT_member_partnerMapper
						.findT_member_partnersByMapListPage(params, page);

				if (partner_members.size() == 0) {
					// 我的核伙机构名
					homePage.setPartner_org_name("");
					// 我的核伙人二维码
					homePage.setPartner_QRcode("");
					// homePage.setAddress("");
				} else {
					homePage.setPartner_org_name(partner_members.get(0)
							.getCorp_name());
					homePage.setPartner_QRcode(partner_members.get(0)
							.getQrcode_img());
					if (type == 1) {
						// 地址
						String address = partner_members.get(0).getAddress();
						address = address.replaceAll("%", "");
						address = address.replaceAll(":", "");
						homePage.setAddress(address);

						String org_address = partner_members.get(0)
								.getAddress();
						org_address = org_address.substring(0,
								org_address.indexOf(":"));

						homePage.setPartner_org_address(org_address.replace(
								"%", " "));
					}
				}
				// 核伙人任务完成情况
				if (type == 1) {
					// params.clear();
					// params.put("user_id", user_id);
					// params.put("status","1");
					// List<ApiT_member_partner> my_partners =
					// this.apiT_member_partnerMapper.findT_member_partnersByMapListPage(params,
					// page);
					// ApiT_member_partner my_partner = my_partners.get(0);

					List<MemberObject> user_task_list = new ArrayList<MemberObject>();
					params.clear();
					params.put("user_id", member.getCid().toString());
					List<ApiT_member_task_process> task_process_list = this.apiT_member_task_processMapper
							.findMemberTaskProcesssByMap(params);
					if (task_process_list.size() > 0) {
						ApiT_member_partner_task task = this.apiT_member_partner_taskMapper
								.findT_member_partner_taskById(Integer
										.valueOf(task_process_list.get(0)
												.getTask_id()));
						MemberObject em = new MemberObject();
						if (task_process_list.get(0).getTask_is_finish() == 0) {
							em.setMember_name(DateUtil
									.restTimeStr(task_process_list.get(0)
											.getDead_time()));
							// em.setMember_name(DateUtil.restTimeStr(my_partner.getRule_deadline()));
						}
						if (task_process_list.get(0).getTask_is_finish() == 1) {
							em.setMember_name("已完成");
						}
						if (task_process_list.get(0).getTask_is_finish() == 2) {
							em.setMember_name("已超时");
						}
						// Integer partnerPer = 100 *
						// task_process_list.get(0).getCurr_partner_count()
						// / task.getInvite_partner_amount();
						if (task_process_list.get(0).getTask_id().equals("1")) {
							String temp = task_process_list.get(0)
									.getCurr_ent_count()
									+ ":"
									+ task_process_list.get(0)
											.getCurr_advert_money()
									+ ":"
									+ task.getBonus_ratio() + "%";
							em.setMember_id(Integer.valueOf(task_process_list
									.get(0).getProcess_id()));
							em.setDesc(temp);
						} else {
							Integer entrePer = 100
									* task_process_list.get(0)
											.getCurr_ent_count()
									/ task.getInvite_entrepreneur_amount();
							BigDecimal b1 = new BigDecimal("100");
							DecimalFormat myformat = new DecimalFormat("0.0");
							BigDecimal moneyPer = new BigDecimal("0");
							if (!Util.isNull(task_process_list.get(0)
									.getCurr_advert_money())) {
								moneyPer = task_process_list
										.get(0)
										.getCurr_advert_money()
										.multiply(b1)
										.divide(task
												.getAdvert_money()
												.setScale(
														0,
														BigDecimal.ROUND_HALF_DOWN));
							}

							String temp = entrePer + "%:"
									+ myformat.format(moneyPer) + "%:"
									+ task.getBonus_ratio() + "%";
							em.setMember_id(Integer.valueOf(task_process_list
									.get(0).getProcess_id()));// T_member_task_process表的ID
							em.setDesc(temp);
						}

						user_task_list.add(em);
					}
					// else {
					// //金牌不显示任务完成情况，
					// partner_members.size();
					// }
					homePage.setTask_list(user_task_list);
				}
			}
		}
		// 自己/企业主/核伙人
		if (type != 2) {
			// 圈子
			params.clear();
			params.put("user_id", member.getCid().toString());
			params.put("is_delete", "0");
			List<ApiU_circle> circle_list = this.apiU_circleMapper
					.findU_circlesByMapListPage(params, page);
			List<MemberObject> user_circle_list = new ArrayList<MemberObject>();

			for (ApiU_circle circle : circle_list) {
				MemberObject em = new MemberObject();
				em.setMember_id(circle.getId());
				em.setHead_img(circle.getCircle_img());
				em.setMember_name(circle.getCircle_name());
				// 圈子人数getcircle_addedcount
				Integer memberCount = this.apiU_circle_memberMapper
						.getcircle_membercount(circle.getId().toString());
				em.setDesc(memberCount.toString());
				user_circle_list.add(em);
			}
			homePage.setCircle_list(user_circle_list);
			homePage.setCircle_count(circle_list.size());

			// 动态 根据设置判断是否可以查看动态
			ApiU_user_friend_setting friendSetting = apiU_user_friend_settingMapper
					.getFriendSetting(user_id, my_id);
			if (friendSetting == null || friendSetting.getIs_readdynamic() == 0) {
				params.clear();
				params.put("user_id", member.getCid().toString());
				params.put("type", "0");
				List<ApiU_dynamic> dynamic_list = this.apiU_dynamicMapper
						.findU_dynamicsByMapListPage(params, page);
				List<MemberObject> user_dynamic_list = new ArrayList<MemberObject>();
				for (ApiU_dynamic dynamic : dynamic_list) {
					MemberObject em = new MemberObject();
					em.setMember_name(dynamic.getContext());
					em.setMember_id(dynamic.getId());
					em.setDesc(dynamic.getAdd_time());
					params.clear();
					params.put("dynamic_id", dynamic.getId().toString());
					// 动态中第一条图
					String img = "";
					List<ApiU_dynamic_source> dynamic_sources = this.apiU_dynamic_sourceMapper
							.findU_dynamic_sourcesByMap(params);
					if (dynamic_sources.size() == 0) {
						img = "";// 放入默认图片
					} else {
						img = dynamic_sources.get(0).getSource();
					}
					em.setHead_img(img);
					user_dynamic_list.add(em);
				}
				homePage.setDynamic_count(dynamic_list.size());
				homePage.setDynamic_list(user_dynamic_list);
			}
		}

		// 自己，核伙人
		if (type == 1 || type == 3) {
			// 谁看了我
			params.clear();
			params.put("see_uid", member.getCid().toString());
			List<ApiU_see_his> see_his_list = this.apiU_see_hisMapper
					.findU_see_hissByMapListPage(params, page);
			List<MemberObject> see_list = new ArrayList<MemberObject>();
			for (ApiU_see_his his : see_his_list) {
				MemberObject em = new MemberObject();
				em.setMember_id(Integer.valueOf(his.getUser_id()));
				em.setHead_img(his.getC_avatar());
				em.setMember_name(his.getC_nick());
				see_list.add(em);
			}
			homePage.setSee_count(see_his_list.size());
			homePage.setSee_list(see_list);
		}

		// 看别人主页面时，是否是好友
		if (type == 4) {
			ApiU_user_friend user_friend = this.apiU_user_friendMapper
					.checkUserFriendState(user_id, my_id);
			if (!Util.isNull(user_friend)) {
				homePage.setIs_friend(1);
			}
		}
		return homePage;
	}

	// 用户查找
	public List<ApiTmember> findMemberByWords(String user_id, String word,
			PageInfo page) {
		return this.apiTmemberMapper.findMemberByWordsListPage(user_id, word,
				page);
	}

	// 核伙人任务信息
	public ApiT_member_task_process getMemberPartnerTaskInfo(String process_id) {
		ApiT_member_task_process task_process = this.apiT_member_task_processMapper
				.findT_member_task_processById(Integer.valueOf(process_id));
		if (!Util.isNull(task_process)) {
			if (task_process.getTask_is_finish() == 0) {
				task_process.setDead_time(DateUtil.restTimeStr(task_process
						.getDead_time()));
			}
			if (task_process.getTask_is_finish() == 1) {
				task_process.setDead_time("已完成");
			}
			if (task_process.getTask_is_finish() == 2) {
				task_process.setDead_time("已超时");
			}

			ApiT_member_partner_task task = this.apiT_member_partner_taskMapper
					.findT_member_partner_taskById(Integer.valueOf(task_process
							.getTask_id()));
			task_process.setApiT_member_partner_task(task);
			return task_process;
		} else {
			return null;
		}
	}

	// 关注的人列表
	public List<ApiTmember> findFollowMemberList(String user_id, Integer type,
			PageInfo page) {
		return this.apiTmemberMapper.findMemberListByFollowTypeListPage(
				user_id, type, page);
	}

	@Override
	public void updatePwdByMobile(String mobile, String pwd) {
		apiTmemberMapper.updatePwdByMobile(mobile, pwd);
	}

	@Override
	public ApiTmember checkPayPass(String userId, String pwd) {
		// TODO Auto-generated method stub
		return apiTmemberMapper.checkPayPass(userId, pwd);
	}

	@Transactional
	public Map<String, Object> wxreceivebonus(String cMob, String code,
			String bonus_detail_id) throws Exception {
		Map<String, Object> map;

		map = new HashMap<String, Object>();
		ApiSmslog apiSmslog = new ApiSmslog();
		apiSmslog.setcTel(cMob);
		apiSmslog.setCode(code);
		ApiSmslog apiSmslog1 = apiSmslogMapper.checkCode(apiSmslog);
		// 判断手机验证码是否正确
		if (apiSmslog1 != null) {
			ApiU_bonus_detail apiU_bonus_detail = apiU_bonus_detailMapper
					.findU_bonus_detailById(Integer.valueOf(bonus_detail_id));
			if (apiU_bonus_detail.getStatus() == 1) {
				map.put(Utils.RESULT, Utils.RESULT_RC_EXIST);
				map.put(Utils.MESSAGE, "红包已领取，不可重复领取！");
			} else if (apiU_bonus_detail.getStatus() == 2) {
				map.put(Utils.RESULT, Utils.RESULT_RC_EXIST);
				map.put(Utils.MESSAGE, "红包已退回，无法领取！");
			} else {
				ApiTmember tmember = apiTmemberMapper.findMemberByCuserid(cMob);
				if (tmember != null) {// 用户存在
					String fromuserid = apiU_bonus_detail.getGet_uid();
					// 领取红包
					apiU_bonus_detail.setGet_uid(tmember.getCid() + "");
					apiU_bonus_detail.setGet_uhead(tmember.getCavatar());
					apiU_bonus_detail.setGet_uname(tmember.getCnick());
					apiU_bonus_detail.setStatus(2);
					apiU_bonus_detailMapper
							.updateU_bonus_detail(apiU_bonus_detail);

					// 更新用户余额
					tmember.setCmoney(tmember.getCmoney().add(
							apiU_bonus_detail.getMoney()));
					apiTmemberMapper.updateApiTmember(tmember);

					ApiT_user_cash_records apiT_user_cash_records = new ApiT_user_cash_records();
					apiT_user_cash_records.setUser_id(tmember.getCid() + "");
					apiT_user_cash_records.setCate_type(6);
					apiT_user_cash_records.setCreate_time(DateUtil
							.nowTimeToString());
					apiT_user_cash_records.setMoney(apiU_bonus_detail
							.getMoney());
					apiT_user_cash_records.setOrder_id("");
					apiT_user_cash_records.setRemark("领红包");
					apiT_user_cash_records.setPay_type(1);
					apiT_user_cash_records.setPay_type_desc("");
					// 根据是否是充值订单判断是收入还是支出
					apiT_user_cash_records.setProcess_type(0);
					apiT_user_cash_recordsMapper
							.T_user_cash_recordsInsertion(apiT_user_cash_records);

					// 消息
					List<ApiU_message> list = new ArrayList<ApiU_message>();
					ApiU_message message = new ApiU_message();
					message.setAdd_time(DateUtil.nowTimeToString());
					message.setConn_id(apiU_bonus_detail.getId());
					message.setTitle("红包");
					message.setType(4);
					message.setUser_id(tmember.getCid().toString());
					message.setIs_read(0);
					message.setContent("您已领取了一个金额为："
							+ apiU_bonus_detail.getMoney() + " 元的红包");
					list.add(message);

					ApiU_message message2 = new ApiU_message();
					message2.setAdd_time(DateUtil.nowTimeToString());
					message2.setConn_id(apiU_bonus_detail.getId());
					message2.setTitle("红包");
					message2.setType(4);
					message2.setUser_id(fromuserid);
					message2.setIs_read(0);
					message2.setContent(tmember.getCnick() + " 领取了你分享的红包");
					list.add(message2);
					apiU_messageMapper.insertmessageList(list);

					map.put(Utils.RESULT, "0000");
					map.put(Utils.MESSAGE, "成功领取");
					map.put(Utils.DATAS, apiU_bonus_detail.getMoney() + "");
				} else { // 用户不存在 则将红包金额和用户的关系存入库中
					ApiU_share_bonus apiU_share_bonus = new ApiU_share_bonus();
					apiU_share_bonus.setBonus_detail_id(Integer
							.valueOf(bonus_detail_id));
					apiU_share_bonus.setCreate_time(DateUtil.nowTimeToString());
					apiU_share_bonus.setPhone(cMob);
					apiU_share_bonusService
							.U_share_bonusInsertion(apiU_share_bonus);
					map.put(Utils.RESULT, "0001");
					map.put(Utils.MESSAGE, "请下载app领取红包");
				}
			}
		} else {
			map.put(Utils.RESULT, "0002");
			map.put(Utils.MESSAGE, "验证码不匹配，请重新填写！");
		}

		return map;
	}

	@Transactional
	public void resetPayPwd(ApiTmember member, ApiSmslog apiSmslog)
			throws Exception {
		apiTmemberMapper.updateApiTmember(member);
		// 更新验证码状态-已验证
		apiSmslogService.updateSmslog(apiSmslog);

	}

	// 注册新用户
	@Transactional
	public Map<String, Object> registmember(ApiTmember member,
			ApiT_member_idcard idcard, ApiSmslog apiSmslog, String payimgurl)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		if (apiSmslogMapper.checkCode(apiSmslog) == null) {// 验证码不通过
			map.put(Utils.RESULT, "0002");
			map.put(Utils.MESSAGE, "验证码不匹配，请重新注册");
			return map;
		}
		ApiTmember invitepeople = new ApiTmember();
		if (!Util.isNull(member.getC_invitecode())) {
			invitepeople = apiTmemberMapper.findMemberByCode(member
					.getC_invitecode());
			if (invitepeople == null) {
				map.put(Utils.RESULT, "0002");
				map.put(Utils.MESSAGE, "邀请码错误，没有改会员");
				return map;
			}
		}

		String superiorcode = member.getC_superior();// 上线的会员编码
		Integer c_proxyid = member.getC_proxyid();// 註冊的代理等级

		if (c_proxyid != 1) {// 非董事，必须有上线的会员编 码，且上线的人员的代理等级必须比本人高
			Integer error = registmember(c_proxyid, superiorcode);
			if (error == 0) {
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "上线的会员编号不能为空,且上线会员等级必须高于你");
				return map;
			} else if (error == 1) {
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "上线会员编码错误,没有找到该会员");
				return map;
			} else if (error == 3) {
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "上线的会员的代理等级過低，请重新注册");
				return map;
			}
		}

		String nowStr = DateUtil.nowTimeToString();
		ApiD_proxy pD_proxy = apiD_proxyMapper.findD_proxyById(member
				.getC_proxyid());

		member.setC_code(UUIDUtil.generateString(6));// 生成邀请码
		member.setC_membercode(UUIDUtil.generateString(8));// 生成會会员码
		member.setC_authcode(UUIDUtil.generateString(32));// 生成授权码
		member.setIs_allow(0);// 默認不能登錄
		member.setVerify_idcard(2); // 实名认证中
		member.setCmoney(pD_proxy.getDeposit());// 门槛金充值到余额中
		member.setCregdate(nowStr);
		ApiTmember apiTmember = apiTmemberMapper.findMemberByCuserid(member
				.getCuserid());

		// 更新验证码状态
		apiSmslogMapper.updateSmslog(apiSmslog);
		// 保存注册用户信息
		apiTmemberMapper.saveApiTmember(member);
		// 添加实名认证记录
		idcard.setUser_id(member.getCid());
		idcard.setApply_time(nowStr);
		idcard.setStatus(0);
		apiT_member_idcardMapper.insertT_member_idcard(idcard);

		// 如果是被邀请加入，则邀请记录表添加数据
		if (!Util.isNull(member.getC_invitecode())) {
			ApiD_invite_record invite_record = new ApiD_invite_record();
			invite_record.setCreate_time(nowStr);
			invite_record.setInviteeid(member.getCid());
			invite_record.setInviterid(invitepeople.getCid());
			if (invitepeople.getC_proxyid() > member.getC_proxyid()) {
				invite_record.setType(1);
			} else if (invitepeople.getC_proxyid() < member.getC_proxyid()) {
				invite_record.setType(2);
			} else {
				invite_record.setType(0);
			}
			invite_recordMapper.D_invite_recordInsertion(invite_record);
		}

		// 添加交保证金的订单记录
		ApiT_order t_order = new ApiT_order();
		t_order.setTitles("注册交门槛金");
		t_order.setUser_id(member.getCid() + "");
		if (member != null) {
			t_order.setName(member.getCnick());// 根据userId获取
			t_order.setTel(member.getCtel());// 根据userId获取
			t_order.setMobile(member.getCtel());// 根据userId获取
		}
		t_order.setMoney(pD_proxy.getDeposit());
		t_order.setMobile(member.getCmob());
		t_order.setAppdate(nowStr);
		t_order.setPaytime(nowStr);
		t_order.setEnable(5);// 完成订单
		t_order.setZi_status(1);// 已支付
		t_order.setDd_status(2);// 未支付
		t_order.setOrdertype(12);// 12-注册交保证金
		t_order.setOrdernum(UUIDUtil.generateString(16));
		t_order.setSerialflagno(UUIDUtil.generateString(32));
		apiT_orderMapper.T_orderInsertion(t_order);

		// 用户金额变动表记录
		ApiT_user_cash_records apiT_user_cash_records = new ApiT_user_cash_records();
		apiT_user_cash_records.setUser_id(member.getCid() + "");
		apiT_user_cash_records.setRemark("注册交门槛金");
		apiT_user_cash_records.setCate_type(9);
		apiT_user_cash_records.setCreate_time(nowStr);
		apiT_user_cash_records.setMoney(pD_proxy.getDeposit());
		apiT_user_cash_records.setOrder_id(t_order.getRid() + "");
		apiT_user_cash_records.setPay_type(2);
		apiT_user_cash_records.setPay_type_desc("4");
		apiT_user_cash_records.setProcess_type(0);
		apiT_user_cash_recordsMapper
				.T_user_cash_recordsInsertion(apiT_user_cash_records);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "注册成功");
		map.put("datas", member);

		return map;
	}

	/**
	 * 根据会员编码获取会员信息
	 */
	public Map<String, Object> getMemberInfoByMembercode(String membercode)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		ApiTmember mTmember = apiTmemberMapper
				.findMemberByMemberCode(membercode);
		if (mTmember == null) {
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "会员编码错误，没有找到该会员");
			return map;
		}
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "注册成功");
		map.put("datas", mTmember);
		return map;
	}

	/**
	 * 验证上线会员的代理等级是不是比proxyid代表的等级要高， 返回值0-上线的会员码为空；1-上线的会员码错误，找不到该会员
	 * 2-上线会员的代理级别比选择的代理级别高；3-上线会员的代理级别比选择的代理级别低
	 */
	public Integer registmember(Integer proxyid, String c_membercode) {
		if (Util.isNull(c_membercode)) {
			return 0;
		}
		ApiTmember superiormember = apiTmemberMapper
				.findMemberByMemberCode(c_membercode);
		if (superiormember == null) {
			return 1;
		}
		if (proxyid > superiormember.getC_proxyid()) {
			return 2;
		} else {
			return 3;
		}
	}
}
